package p.wechat.zwapi.api.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import p.wechat.zwapi.api.WeChatApi;
import p.wechat.zwapi.basis.WeChatApiFuncType;
import p.wechat.zwapi.basis.WeChatApiMsgType;
import p.wechat.zwapi.dto.Message;
import p.wechat.zwapi.util.WeChatHttpUtil;

import java.io.File;
import java.util.Objects;

@Slf4j
public class WeChatApiUtil implements WeChatApi {



    public static Message get() {
        Message message = WeChatApi.LOCAL.get();
        if (message == null) {
            log.warn("数据异常");
        }
        return message;
    }

    /**
     * 收到消息
     *
     * @param message 消息
     * @return {@link Object}
     */
    @Override
    public Object receivedTheNews(String message) {
        WeChatApi.LOCAL.set(JSONUtil.toBean(message, Message.class));
        Message m = get();
        if (m.getWxid().contains("@chatroom")) {
            // TODO: 2020/8/17 这是群聊信息
            return false;
        }

        if (Objects.equals(1, m.getAttach2()) && Objects.equals(m.getWxid(),WeChatApi.FILEHELPER)==false) {
            // TODO: 2020/8/17 这里是自己发给别人的信息
            return false;
        }
        if (log.isDebugEnabled()) {
            log.debug("收到信息:{}", message);
        }

        SimpleMessageProcessing.send(m);
        return null;
    }

    @Override
    public Object 发送信息(String content) {
        return 发送信息(content, WeChatApiFuncType.发送文本);
    }

    @Override
    public Object 发送图片(String content) {
        return 发送信息(content, WeChatApiFuncType.发送图片);
    }

    @Override
    public Object 发送信息(String content, WeChatApiFuncType weChatApiFuncType) {
        return 发送信息(get().getWxid(), content, weChatApiFuncType);
    }

    @Override
    public Object 发送信息(String wxid, String content, WeChatApiFuncType weChatApiFuncType) {
        WeChatHttpUtil.exec(new Message().setContent(content).setWeChatID(get().getWeChatID()).setWxid(wxid).setFunid(weChatApiFuncType.getValue()));
        return null;
    }

    @Override
    public Object 获取当前启动微信数目和登录信息() {
        return  WeChatHttpUtil.execJSONArr(new Message().setFunid(10));
    }

    @Override
    public Object 创建微信() {
         return WeChatHttpUtil.exec(new Message().setFunid(11));
    }

    @Override
    public Object 退出登录(Integer weChatID) {
        return WeChatHttpUtil.exec(new Message().setFunid(WeChatApiFuncType.退出登录.getValue()).setWeChatID(weChatID));
    }


    @Override
    public Object 发送名片(String msg) {
        return 发送名片(msg, get().getWeChatID());
    }

    @Override
    public Object 发送名片(String msg, Integer weChatID) {
        return 发送名片(get().getWxid(), msg, weChatID);
    }

    @Override
    public Object 发送名片(String wxid, String msg, Integer weChatID) {
        WeChatHttpUtil.exec(new Message().setFunid(WeChatApiFuncType.发送名片.getValue()).setWeChatID(weChatID).setContent(msg).setWxid(wxid));
        return null;
    }

    @Override
    public Object 同意好友请求() {
        Message message = get();

        Document document = XmlUtil.readXML(message.getContent());
        NamedNodeMap attributes = document.getElementsByTagName("msg").item(0).getAttributes();

        String encryptusername = attributes.getNamedItem("encryptusername").getNodeValue();
        String ticket = attributes.getNamedItem("ticket").getNodeValue();
        String fromusername = attributes.getNamedItem("fromusername").getNodeValue();// 微信id

        WeChatHttpUtil.exec(new Message().setWeChatID(message.getWeChatID()).setFunid(WeChatApiFuncType.同意好友请求.getValue()).setV1(encryptusername).setV4(ticket));
        ThreadUtil.sleep(2000);
        发送信息(fromusername, "通过", WeChatApiFuncType.发送文本);
        return null;
    }

    @Override
    public Object 接收转账() {
        Message message = get();

        if (Objects.equals(1, message.getAttach2())) {
            return null;
        }
        Document document = XmlUtil.readXML(message.getContent());
        String paysubtype = document.getDocumentElement().getElementsByTagName("paysubtype").item(0).getTextContent(); //转账类型
        if (Objects.equals(paysubtype, "3")) {
            return false;
        }
        String transferid = document.getDocumentElement().getElementsByTagName("transferid").item(0).getTextContent();
        String pay_memo = document.getDocumentElement().getElementsByTagName("pay_memo").item(0).getTextContent(); //  转账备注
        String feedesc = document.getDocumentElement().getElementsByTagName("feedesc").item(0).getTextContent(); //  转账金额

        ThreadUtil.sleep(1000);
        WeChatHttpUtil.exec(new Message().setWeChatID(message.getWeChatID()).setFunid(WeChatApiFuncType.收款.getValue()).setTransferid(transferid).setWxid(message.getWxid()));
        发送信息(StrUtil.format("自动收款\n金额:{}\n备注:{}", feedesc, pay_memo));
        return null;
    }

    @Override
    public Object 获取好友列表(Integer weChatID) {
        return WeChatHttpUtil.exec(new Message().setWeChatID(weChatID).setFunid(WeChatApiFuncType.好友列表.getValue()));
    }

    @Override
    public Object 获取群成员列表(Integer weChatID,String qunId) {

        return WeChatHttpUtil.exec(new Message().setFunid(WeChatApiFuncType.获取群成员列表.getValue()).setWxid(qunId).setWeChatID(weChatID));
    }

    @Override
    public Object 查询信息(Integer weChatID, String wxId) {
        return WeChatHttpUtil.exec(new Message().setWxid(wxId).setWeChatID(weChatID).setFunid(WeChatApiFuncType.查询信息.getValue()));
    }

    @Override
    public Object 群创建(String wxIds) {
        return null;
    }

}

/**
 * 简单消息处理
 *
 * @author 33
 * @date 2020/08/17
 */
@Slf4j
class SimpleMessageProcessing {

    static WeChatApi f = new WeChatApiUtil();


    public static JSONObject send(Message message) {
        if (Objects.equals(message.getWxid(), WeChatApi.FILEHELPER)) {
            if (Objects.equals(message.getContent(), "新开微信")) {
                WeChatHttpUtil.exec(new Message().setFunid(11));
                ThreadUtil.sleep(4000);
                JSONArray objects = WeChatHttpUtil.execJSONArr(new Message().setFunid(10));
                for (Object object : objects) {
                    JSONObject jsonObject = (JSONObject) object;
                    JSONObject data = jsonObject.getJSONObject("data");
                    String qrcode = data.getStr("qrcode");
                    if (StrUtil.isNotBlank(qrcode)) {
                        File file = new File("微信临时二维码".concat(RandomUtil.randomString(10) + ".jpg"));
                        QrCodeUtil.generate(qrcode, 300, 300, file);
                        String exec = WeChatHttpUtil.exec(new Message().setWeChatID(message.getWeChatID()).setWxid(message.getWxid()).setContent(file.getAbsolutePath()).setFunid(WeChatApiFuncType.发送图片.getValue()));
                        ThreadUtil.execAsync(() -> {
                            ThreadUtil.sleep(6000);
                            FileUtil.del(file);
                        });
                    }
                }
            }
        }

        switch (WeChatApiMsgType.getType(message.getType())) {
            case 收到好友请求: {
                f.同意好友请求();
                break;
            }
            case 收到转账: {
                f.接收转账();
                break;
            }
            case 收到名片:{
                f.发送名片(message.getContent());
                break;
            }
        }

        return null;
    }
}
